<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" :closable="false" type="info" show-icon></el-alert>
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        label-position="top"
        :model="GoodListForm"
        :rules="GoodListRules"
        ref="GoodListRef"
        label-width="100px"
      >
        <el-tabs
          :before-leave="TabChange"
          tab-position="left"
          v-model="activeIndex"
          @tab-click="tabChangeNum"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="GoodListForm.goods_name"></el-input>s
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="GoodListForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="GoodListForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="GoodListForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_introduce">
              <el-cascader
                v-model="cardAss"
                :options="createdAccList"
                :props="prop"
                @change="cardAssHandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in tabsData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item2" v-for="(item2,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :headers="handerToken"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="priDataSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="GoodListForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addContent">添加内容</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="dialogTableVisible" width="30%">
      <img :src="perventPath" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: 0,
      GoodListForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        pics: [],
        goods_introduce: "",
        goods_cat: "",
        attrs: []
      },
      perventPath: "",
      dialogTableVisible: false,
      onlyData: [],
      tabsData: [],
      cardAss: [1, 3, 6],
      createdAccList: [],
      prop: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id"
      },
      handerToken: {
        Authorization: sessionStorage.getItem("token")
      },
      GoodListRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_introduce: [
          { required: true, message: "请输入商品介绍", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品分类", trigger: "blur" }
        ]
      }
    };
  },

  methods: {
    async getCascList() {
      const res = await this.axios.get("categories");
      if (res.meta.status !== 200) return this.$mg.error(res.meta.msg);
      this.$mg.success(res.meta.msg);
      this.createdAccList = res.data;
    },
    cardAssHandleChange() {
      if (this.cardAss.length != 3) this.cardAss = [];
    },
    TabChange(newa, old) {
      if (old === "0" && this.cardAss.length != 3) {
        this.$mg.error("请选择三级分类");
        return false;
      }
    },
    // 点击tab栏获得值 判断是否能发送请求
    async tabChangeNum() {
      if (this.activeIndex == "1") {
        const res = await this.axios.get(
          `categories/${this.cardAss[2]}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        if (res.meta.status != 200) return;
        this.tabsData = res.data;
        console.log(this.tabsData);
      } else if (this.activeIndex == "2") {
        const res = await this.axios.get(
          `categories/${this.cardAss[2]}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );

        if (res.meta.status != 200) return;
        this.onlyData = res.data;
        console.log(this.onlyData);
      }
    },
    handlePreview(file) {
      this.perventPath = file.response.data.url;
      this.dialogTableVisible = true;
    },
    handleRemove(file) {
      let filepath = file.response.data.tmp_path;
      let index = this.GoodListForm.pics.findIndex(item => {
        return item.pic == filepath;
      });
      this.GoodListForm.pics.splice(index, 1);
      console.log(this.GoodListForm.pics);
    },
    priDataSuccess(res) {
      if (res.meta.status == 200)
        this.GoodListForm.pics.push({
          pic: res.data.tmp_path
        });
      console.log(this.GoodListForm);
    },
    addContent() {
      this.GoodListForm.goods_cat = this.cardAss.join(",");
      this.tabsData.forEach(item => {
        this.GoodListForm.attrs.push({
          attr_id: item.attr_id,
          attr_vals: item.attr_vals
        });
      });
      this.onlyData.forEach(item => {
        this.GoodListForm.attrs.push({
          attr_id: item.attr_id,
          attr_vals: item.attr_vals
        });
      });
      this.$refs.GoodListRef.validate(async falg => {
        if (!falg) return;
        const res = await this.axios.post("goods/", this.GoodListForm);
        if (res.meta.status !== 201) return this.$mg.error(res.meta.msg);
        this.$mg.success(res.meta.msg);
        this.$router.push("/goods");
      });
    }
  },
  created() {
    this.getCascList();
  }
};
</script>

<style lang='less' scoped>
.el-alert {
  display: flex;
  justify-content: center;
}
.el-step__main .el-step__title {
  font-size: 12px;
}
.el-tabs {
  margin-top: 15px;
}
.el-button {
  margin: 10px;
}
</style>

